class Iteration < ActiveRecord::Base
  has_many :deliverables, :as => :schedulable, :dependent => :destroy

  validates_numericality_of :iteration_number
  validates_date :start_date
  validates_date :end_date, :after => :start_date

  def validate
    if self.start_date < Iteration.most_recent_iteration.end_date 
      errors.add(:start_date, ": A new Iteration cannot be started until the current Iteration ends. The current iteration ends on #{Iteration.most_recent_iteration.end_date}")
    end
  end

  def Iteration.default
    Iteration.new(
      :iteration_number => 0,
      :start_date => Date.today - 1,
      :end_date => Date.today
    )
  end

  def Iteration.most_recent_iteration
    iteration = Iteration.find(:all).max do |a, b|
      a.start_date <=> b.start_date
    end

    iteration || Iteration.default
  end

  def get_deliverables_for_resource(resource)

    result = []

    #find deliverables that match the specified resource
    deliverables.each do |deliverable|

      deliverable.assignments.each do |assignment|

        if assignment.resource.name == resource
          result << deliverable
        end
      end
    end 

    return result
  end



  #
  # Clones deliverables that have been marked as
  # 'Moved to next iteration'
  def clone_deliverables_for_next_iteration

    result = []

    deliverables.each do |deliverable|

      #Deliverables that are marked to be moved to the next
      #iterations should be copied
      if deliverable.status == "Moved to next iteration" 

        #clone the deliverable
        cloned_deliverable = deliverable.deep_clone

        # set the status to empty
        cloned_deliverable.status = ""
        result << cloned_deliverable
      end
    end

    result
  end

  def Iteration.get_completion_status(deliverables)
    status = ""
    completed = 0
    deliverables.each do |deliverable|
      if deliverable.status == "Complete" 
        completed = completed + 1
      end
    end

    if deliverables.length > 0
      percentage_complete = completed*100/deliverables.length
      status = " #{completed} of #{deliverables.length} deliverables complete (#{percentage_complete}%)"
    end
  
    return status
  end

  def add_deliverables_from_most_recent_iteration
    deliverables_to_move = Iteration.most_recent_iteration.clone_deliverables_for_next_iteration
    if deliverables_to_move.length > 0 
      deliverables << deliverables_to_move
    end
  end

  def clone_and_add_deliverable(deliverableToAdd)
    cloned_deliverable = deliverableToAdd.clone
    cloned_deliverable.status = ""

    cloned_deliverable.resource_names = deliverableToAdd.resource_names

    deliverables << cloned_deliverable
    self.save
  end
end
